//
//  HomeTableViewController.swift
//  weibo
//
//  Created by sanya on 15/6/23.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeTableViewController: BaseTableViewController,StatusCellDelegate {

    var isSelected = false
    var titleButton = HomeTitleButton()
    // 定义缓存的缓存 [statusId:行高]
    lazy var rowHeightCache = [Int: CGFloat]()
    
    
    /// 表格绑定的微博数据数组
    var statusesList: [Status]?{
        didSet{
            // 刷新表格
            tableView.reloadData()
            
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

    visitorView?.setUpViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        if userLogin == false{
            return
        }
        setupNavigationBar()
        prepareTableView()
        
        
        refreshControl = SYRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        loadData()
        

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        rowHeightCache.removeAll()
    }
    private func prepareTableView(){
        // 注册可重用cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: SYForwardPictureCellReuseIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: SYNormalPictureCellReuseIdentifier)
        
        // 设置行高
        //        tableView.estimatedRowHeight = 200
        //        tableView.rowHeight = 300
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
//        tableView.showsVerticalScrollIndicator = false
    
    }
    
    override func viewDidAppear(animated: Bool) {
        visitorView?.startAnimation()
    }

    // 下拉刷新的代号，取到数组中的第一条数据的 id
    
    func loadData(){
        // 开始刷新-不会触发监听方法，会显示刷新控件
        refreshControl?.beginRefreshing()
        // 下拉刷新的代号，取到数组中第1条数据的 id
        var since_id = statusesList?.first?.id ?? 0
        // 上拉刷新，取到数组中最后1条数据的 id
        var max_id = 0
        if pullRefreshFlag {
            since_id = 0
            max_id = statusesList?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            if error != nil {
                SVProgressHUD.showInfoWithStatus("你的网络不给力啊")
                return
            }
            if statuses == nil{
                print("没有数据")
                return
            }
//            for s in statuses! {
//                if s.retweeted_status != nil {
//                    print("转发微博 \(s.text)")
//                }
//            }
            // 跟踪转发微博
            print("加载了 \(statuses?.count) 条微博")
            
            if since_id > 0 {
                // 下拉刷新
                self.statusesList = statuses! + self.statusesList!
            }else if max_id > 0 {
                // 上拉刷新
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = true
            }else{
                // 初始刷新
                self.statusesList = statuses
            }
            
        }
    
    }
    /// 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return statusesList?.count ?? 0
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let status = statusesList![indexPath.row]
        // 此方法必须注册可重用cell，如果不注册，会崩溃
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCell.cellIdentifier(status), forIndexPath: indexPath) as! StatusCell
        
        // 设置 cell
        cell.status = statusesList![indexPath.row]
        // 判断是否是最后一行
        if indexPath.row == statusesList!.count - 1 {
            pullRefreshFlag = true
            loadData()
        }
        cell.photoDelegate = self

        return cell
    }
    /// 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 1. 取到对象
        let status = statusesList![indexPath.row]
        // 1.1 判断是否有行高缓存
        if rowHeightCache[status.id] != nil{
//            print("返回缓存行高")
            return rowHeightCache[status.id]!
        }
        
        // 2. 获取cell - 从可重用的 缓冲池 中提取一个cell，说明之前用过，要计算行高准确，需要实例化一个cell
        // Xcode 7.0 新发现的
        // 2.1 取可重用的ID
        let ID = StatusCell.cellIdentifier(status)
        // 2.2 定义一个类， 默认是原创微博的 cell
        var cls:AnyClass = StatusNormalCell.self
        // 2.3 根据ID判断是否为转发微博
        if ID == SYForwardPictureCellReuseIdentifier {
            cls = StatusForwardCell.self
        }
        // 2.4 根据cls 创建cell
        let cell = cls.new() as! StatusCell
        
        // 3.返回行高
        let height = cell.rowheight(status)
        rowHeightCache[status.id] = height
        return height
    }
    /// photoDelegate 代理方法
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
        if cell.status?.largePicURLs == nil{
            return
        }
        // 传递数据！ -图像的数组 & 用户选中额照片索引
        let vc = PhotoBrowserViewController(urls: cell.status!.largePicURLs!, index: photoIndex)
        // 设置转场代理
        vc.transitioningDelegate = self
        // 设置转场的方式
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        presentViewController(vc, animated: true, completion: nil)
    }

    
    // 下拉菜单
    func showQRCode(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    
    }
    // 设置navigiationBar
    private func setupNavigationBar(){
        // 判断用户是否登录
        if sharedUserAccount == nil{
            return
        }
        
        // 设置左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil)
        // 设置右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil)
        let btn = navigationItem.rightBarButtonItem!.customView as! UIButton
        btn.addTarget(self, action: "showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 中间标题
        titleButton = HomeTitleButton.button(sharedUserAccount!.name!)

        titleButton.addTarget(self, action: "titleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeBtn", name: "changeBtnstatus", object: nil)
    }
    
    var popoverAnimator = PopoverAnimator()
    
    
    // 改变title的图片
    func changeBtn(){
        
        isSelected = !isSelected
        let btnImageName = isSelected ? "navigationbar_arrow_up":"navigationbar_arrow_down"
        titleButton.setImage(UIImage(named: btnImageName), forState: UIControlState.Normal)
    }
    // titleButton的点击事件
    func titleButtonClick(btn:UIButton){

        self.changeBtn()
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vp = sb.instantiateViewControllerWithIdentifier("popover")
        
        // 设置转场的代理
        vp.transitioningDelegate = popoverAnimator
        // 设置视图的展现大小
        let x = (view.frame.width - 200) * 0.5
        print(x)
        popoverAnimator.presentedFrame = CGRectMake(x, 56, 200, 250)
        // 设置转场的模式-自定义转场动画
        vp.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vp, animated: true, completion: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver("changeBtnstatus")
    }
    // 上拉刷新标记
    private var pullRefreshFlag = false
    private var isPresented = false
}
extension HomeTableViewController:UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning {

    // 返回提供转场 Modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    // 返回提供转场 Dismiss 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    // 动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    // 一旦实现需要程序员自定义动画
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        // 1. 获取目标视图
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        if isPresented {
            // 添加toView
            transitionContext.containerView()?.addSubview(targetView!)
            targetView?.alpha = 0
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView?.alpha = 1
                }, completion: { (_) -> Void in
                    // 告诉动画已经完成
                    transitionContext.completeTransition(true)
            })
            
        }else {
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView?.alpha = 0
                }, completion: { (_) -> Void in
                    transitionContext.completeTransition(true)
            })
        }

    }
}
